﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Web.UI.WebControls;
using System.Web.UI;
using Microsoft.SharePoint;
using System.Text.RegularExpressions;

namespace TRIG_MOD_DASHBOARDS
{
    class DataForUsersTasks
    {
        public Label errorMsg { get; set; }

        public static DataTable CreateDataColumns(params string[] colna)
        {
            DataTable dt = new DataTable();
            foreach (string item in colna)
            {
                dt.Columns.Add(item);
            }
            return dt;
        }

        public static void CreateLinkButton(string LinkText, string OnClickScript, GridViewRowEventArgs e, int ColumnNumber, bool EnableButton)
        {
            LinkButton lb = new LinkButton();
            lb.Text = LinkText;
            if (OnClickScript.StartsWith("javascript:"))
                lb.OnClientClick = OnClickScript;
            else
                lb.Attributes.Add("onclick", "loadFile(" + OnClickScript + ");");

            lb.Enabled = EnableButton;
            e.Row.Cells[ColumnNumber].Controls.Add((Control)lb);
        }

        #region "Get TaskLists by Datatable"

        public static DataTable GetItemsOfSpecificTypeFromWeb(string camQ, SPListTemplateType ListTemplateType)
        {
            using (SPSite oSite = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    SPSiteDataQuery sQuery;
                    sQuery = new SPSiteDataQuery();
                    if (ListTemplateType.ToString() == "Tasks")
                        sQuery.Lists = "<Lists ServerTemplate='107' />"; //SPListTemplateType.Tasks
                    else
                        sQuery.Query = camQ;
                    return oWeb.GetSiteData(sQuery);
                }
            }
        }

        public static DataTable GetItemsOfSpecificTypeFromWeb(Guid SiteGid, Guid WebGid, string camQ, SPListTemplateType ListTemplateType)
        {
            SPWeb oWeb = new SPSite(SiteGid).OpenWeb(WebGid);
            SPSiteDataQuery sQuery;
            sQuery = new SPSiteDataQuery();
            if (ListTemplateType.ToString() == "Tasks")

                sQuery.Lists = "<Lists ServerTemplate='107' />"; //SPListTemplateType.Tasks
            else if (ListTemplateType.ToString() == "XMLForm")
                sQuery.Lists = "<Lists ServerTemplate='115' />";
            sQuery.Query = camQ;
            return oWeb.GetSiteData(sQuery);
        }

        #endregion

        #region "Pending Task by Person"

        public int FormLoadBindData(string ddlPerson, GridView gvUserTask)
        {
            string LastAssignedUser = null;
            using (SPSite osite = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb oWeb = osite.OpenWeb())
                {
                    DataTable ToShowDt = CreateDataColumns("DocumentType", "Title", "Related Content", "Status", "Current Revision", "Last Reviewer/Last Approver", "WFOrder", "DocID", "TaskID");
                    DataTable dtN = GetItemsOfSpecificTypeFromWeb(SPContext.Current.Site.ID, oWeb.ID, WFStatus("Not Started", ddlPerson), SPListTemplateType.Tasks);
                    if (dtN.Rows.Count > 0)
                    {
                        try
                        {
                            SPFieldUserValue ofldval = null;
                            SPListItem lstim2 = null;
                            SPListItem oLstItem = null;
                            foreach (DataRow item in dtN.Rows)
                            {
                                SPListItem lstim = oWeb.Lists[new Guid(item[0].ToString())].GetItemById(int.Parse(item[2].ToString()));
                                SPQuery qry = new SPQuery();
                                qry.Query = "<Where><And><Eq><FieldRef Name=\"Status\" /><Value Type=\"Choice\">Completed</Value></Eq><IsNotNull><FieldRef Name=\"AssignedTo\" />" +
                                    "</IsNotNull></And></Where><OrderBy><FieldRef Name=\"Modified\" Ascending=\"False\" /></OrderBy>";

                                if (oWeb.Lists[new Guid(item[0].ToString())].GetItems(qry).Count > 0)
                                {
                                    oLstItem = oWeb.Lists[new Guid(item[0].ToString())].GetItems(qry)[0];

                                    if (oLstItem.ListItems.Count > 0)
                                    {
                                        ofldval = new SPFieldUserValue(oWeb, Convert.ToString(oLstItem["AssignedTo"]));
                                        string user = ofldval.LookupValue; string[] users = user.Split('\\'); var e = from s in users select s; int c = e.Count();
                                        if (c > 1) LastAssignedUser = users[1]; else LastAssignedUser = user;
                                    }
                                }
                                try
                                {

                                    if (ListExist(oWeb, lstim["DocLibID"].ToString()))
                                    {
                                        //lstim2 = oWeb.Lists[new Guid(lstim["DocLibID"].ToString())].GetItemById(int.Parse(lstim["DocID"].ToString()));

                                        lstim2 = getDocItems(oWeb, lstim, lstim["DocLibID"].ToString(), lstim["DocID"].ToString());


                                        //if (lstim2.ListItems.Count > 0)
                                        if (lstim2 != null)
                                        {
                                            if (ofldval != null)
                                            {
                                                ToShowDt.Rows.Add(lstim2.ParentList.Title, lstim2["FileLeafRef"], lstim["Title"], lstim["Status"], lstim["Revision No"], LastAssignedUser + '\n' + lstim["Modified"], lstim["WFOrder"], lstim["DocID"], lstim["ID"]);
                                            }
                                            else
                                            {
                                                ToShowDt.Rows.Add(lstim2.ParentList.Title, lstim2["FileLeafRef"], lstim["Title"], lstim["Status"], lstim["Revision No"], lstim["Modified"] + "  " + string.Empty, lstim["WFOrder"], lstim["DocID"], lstim["ID"]);
                                            }
                                        }
                                        else
                                        {
                                            ToShowDt.Rows.Add(lstim2.ParentList.Title, "No Item found", lstim["Title"], lstim["Status"], lstim["Revision No"], LastAssignedUser + '\n' + lstim["Modified"], lstim["WFOrder"], lstim["DocID"], lstim["ID"]);
                                        }
                                    }
                                    else
                                    {
                                        ToShowDt.Rows.Add("Library not found", "-", lstim["Title"], lstim["Status"], lstim["Revision No"], LastAssignedUser + '\n' + lstim["Modified"], lstim["WFOrder"], lstim["DocID"], lstim["ID"]);
                                    }

                                }
                                catch (Exception x)
                                {
                                    ErrLos(x);
                                }
                            }

                            DisableGridCells(gvUserTask, ToShowDt);
                        }
                        catch (Exception x)
                        {
                            ErrLos(x);
                        }

                    }
                    else
                    {
                        gvUserTask.DataSource = null; gvUserTask.DataBind(); gvUserTask.Visible = false;
                    }

                }
                return gvUserTask.Rows.Count;
            }
        }

        public void Row_Data_Bind(GridViewRowEventArgs e)
        {
            try
            {
                using (SPSite oSite = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb oWeb = oSite.OpenWeb())
                    {
                        if (!string.IsNullOrEmpty(Convert.ToString(e.Row.DataItem)))
                        {
                            SPList oList = oWeb.Lists.TryGetList(e.Row.Cells[0].Text);
                            if (oList != null)
                            {
                                Guid ListID = new Guid(Convert.ToString(oList.ID));
                                if (ListID != null)
                                {
                                    if (!string.IsNullOrEmpty(oList.Title))
                                    {
                                        try
                                        {
                                            SPListItem item = oList.Items.GetItemById(int.Parse(e.Row.Cells[7].Text));
                                            if (item.ListItems.Count > 0)
                                            {
                                                string listurl = string.Empty;
                                                string listViewurl = string.Empty;
                                                if (Convert.ToString(item["FileLeafRef"]) == e.Row.Cells[1].Text)
                                                {
                                                    try
                                                    {
                                                        listurl = "javascript:return DialogDisplay('/_layouts/TRIG_MOD_DASHBOARDS/CustomEdit.aspx?List=" + ListID + "&ID=" + item.ID + "&WF=1&O=" + e.Row.Cells[8].Text + " ');";
                                                        string url = oList.DefaultViewUrl;
                                                        string[] splitter = Regex.Split(url, "Forms");
                                                        if (splitter != null)
                                                        {
                                                            url = splitter[0] + item["FileLeafRef"].ToString();
                                                        }
                                                        string hypercountry = string.Format("<" + "a href='" + url + "'>" + item["FileLeafRef"].ToString() + "</a>");
                                                        e.Row.Cells[1].Text = hypercountry;

                                                    }
                                                    catch (ArgumentException) { }
                                                    catch (NullReferenceException) { }
                                                    CommonMethods.CreateLinkButton("View", listurl, e, 2, true);
                                                }
                                            }
                                            else
                                            {
                                                e.Row.Cells[2].Text = "No records found"; ;
                                            }

                                        }
                                        catch (Exception x)
                                        {
                                            ErrLos(x);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }


            }
            catch (Exception)
            {

                throw;
            }
        }

        #endregion



        #region "Complete Task by Person"

        public int FormLoadBindData(string ddlPerson, GridView gvUserTask, string wfStatus)
        {
            string LastAssignedUser = null;
            using (SPSite osite = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb oWeb = osite.OpenWeb())
                {
                    DataTable ToShowDt = CreateDataColumns("DocumentType", "Title", "Related Content", "Status", "Current Revision", "Last Reviewer/Last Approver", "WFOrder", "DocID", "TaskID");
                    DataTable dtN = GetItemsOfSpecificTypeFromWeb(SPContext.Current.Site.ID, oWeb.ID, WFStatus(wfStatus, ddlPerson), SPListTemplateType.Tasks);
                    if (dtN.Rows.Count > 0)
                    {
                        try
                        {
                            SPFieldUserValue ofldval = null;
                            SPListItem lstim2 = null;
                            SPListItem oLstItem = null;
                            foreach (DataRow item in dtN.Rows)
                            {
                                SPListItem lstim = oWeb.Lists[new Guid(item[0].ToString())].GetItemById(int.Parse(item[2].ToString()));
                                SPQuery qry = new SPQuery();
                                qry.Query = "<Where><And><Eq><FieldRef Name=\"Status\" /><Value Type=\"Choice\">Completed</Value></Eq><IsNotNull><FieldRef Name=\"AssignedTo\" />" +
                                    "</IsNotNull></And></Where><OrderBy><FieldRef Name=\"Modified\" Ascending=\"False\" /></OrderBy>";

                                if (oWeb.Lists[new Guid(item[0].ToString())].GetItems(qry).Count > 0)
                                {
                                    oLstItem = oWeb.Lists[new Guid(item[0].ToString())].GetItems(qry)[0];

                                    if (oLstItem.ListItems.Count > 0)
                                    {
                                        ofldval = new SPFieldUserValue(oWeb, Convert.ToString(oLstItem["AssignedTo"]));
                                    }
                                }
                                try
                                {

                                    if (ListExist(oWeb, lstim["DocLibID"].ToString()))
                                    {
                                        lstim2 = getSPDocItems(oWeb, lstim, lstim["DocLibID"].ToString(), lstim["DocID"].ToString());

                                        if (lstim2 != null)
                                        {
                                            if (ofldval != null)
                                            {
                                                string user = ofldval.LookupValue; string[] users = user.Split('\\'); var e = from s in users select s; int c = e.Count();

                                                if (c > 1) LastAssignedUser = users[1]; else LastAssignedUser = user;

                                                if (lstim2.ParentList.Title != "Inspection Request")
                                                    ToShowDt.Rows.Add(lstim2.ParentList.Title, lstim2["FileLeafRef"], lstim["Title"], lstim["Status"], lstim["Revision No"], LastAssignedUser + '\n' + lstim["Modified"], lstim["WFOrder"], lstim["DocID"], lstim["ID"]);
                                            }
                                            else
                                            {
                                                if (lstim2.ParentList.Title != "Inspection Request")
                                                    ToShowDt.Rows.Add(lstim2.ParentList.Title, lstim2["FileLeafRef"], lstim["Title"], lstim["Status"], lstim["Revision No"], lstim["Modified"] + "  " + string.Empty, lstim["WFOrder"], lstim["DocID"], lstim["ID"]);
                                            }
                                        }
                                        else
                                        {
                                            ToShowDt.Rows.Add(lstim2.ParentList.Title, "Item not found", lstim["Title"], lstim["Status"], lstim["Revision No"], LastAssignedUser + '\n' + lstim["Modified"], lstim["WFOrder"], lstim["DocID"], lstim["ID"]);
                                        }
                                    }

                                    else
                                    {
                                        ToShowDt.Rows.Add("Library not found", "-", lstim["Title"], lstim["Status"], lstim["Revision No"], LastAssignedUser + '\n' + lstim["Modified"], lstim["WFOrder"], lstim["DocID"], lstim["ID"]);
                                    }

                                }
                                catch (Exception x)
                                {
                                    ErrLogs(x);
                                }

                            }

                            DisableGridCells(gvUserTask, ToShowDt);
                        }
                        catch (Exception x)
                        {
                            ErrLogs(x);
                        }


                    }
                    else
                    {
                        gvUserTask.DataSource = null; gvUserTask.DataBind(); gvUserTask.Visible = false;
                    }

                }
                return gvUserTask.Rows.Count;
            }
        }

        public void Row_Data_Bind(GridViewRowEventArgs e, string Complete)
        {
            try
            {
                using (SPSite oSite = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb oWeb = oSite.OpenWeb())
                    {
                        if (!string.IsNullOrEmpty(Convert.ToString(e.Row.DataItem)))
                        {
                            SPList oList = oWeb.Lists.TryGetList(e.Row.Cells[0].Text);
                            Guid ListID = new Guid(Convert.ToString(oList.ID));

                            if (!string.IsNullOrEmpty(oList.Title))
                            {

                                try
                                {
                                    SPListItem item = oList.Items.GetItemById(int.Parse(e.Row.Cells[7].Text));
                                    if (item.ListItems.Count > 0)
                                    {
                                        string listurl = string.Empty;
                                        string listViewurl = string.Empty;
                                        if (Convert.ToString(item["FileLeafRef"]) == e.Row.Cells[1].Text)
                                        {
                                            try
                                            {
                                                listurl = "javascript:return DialogDisplay('/_layouts/TRIG_MOD_DASHBOARDS/CustomEdit.aspx?List=" + ListID + "&ID=" + item.ID + "&WF=1&O=" + e.Row.Cells[8].Text + " ');";
                                                string url = oList.DefaultViewUrl;
                                                string[] splitter = Regex.Split(url, "Forms");
                                                if (splitter != null)
                                                {
                                                    url = splitter[0] + item["FileLeafRef"].ToString();
                                                }
                                                string hypercountry = string.Format("<" + "a href='" + url + "'>" + item["FileLeafRef"].ToString() + "</a>");
                                                e.Row.Cells[1].Text = hypercountry;

                                            }
                                            catch (ArgumentException) { }
                                            catch (NullReferenceException) { }
                                            CommonMethods.CreateLinkButton("View", listurl, e, 2, true);
                                        }
                                    }
                                    else
                                    {
                                        e.Row.Cells[2].Text = "No records found"; ;
                                    }

                                }
                                catch (Exception x)
                                {
                                    ErrLos(x);
                                }

                            }
                        }

                    }
                }


            }
            catch (Exception)
            {

                throw;
            }
        }

        #endregion

        private SPListItem getSPDocItems(SPWeb oWeb, SPListItem lstim, string DocLibID, string DocID)
        {
            SPListItem lstim2 = null;
            try
            {
                lstim2 = oWeb.Lists[new Guid(lstim["DocLibID"].ToString())].GetItemById(int.Parse(lstim["DocID"].ToString()));
                return lstim2;
            }
            catch (Exception x)
            {
                ErrLos(x);
                return null;
            }

        }

        private SPListItemCollection GetSPDocItemCollection(Guid SiteGid, Guid WebGid, string listId, string camQ)
        {
            SPWeb oWeb = new SPSite(SiteGid).OpenWeb(WebGid);
            SPList Tasks = oWeb.Lists[new Guid(listId)];
            SPQuery query = new SPQuery();
            query.Query = camQ;
            SPListItemCollection lstimTasks = Tasks.GetItems(query);
            return lstimTasks;
        }

        public int DocsApprovalStatus(string loginUser, GridView gvAppStatus)
        {
            using (SPSite osite = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb oWeb = osite.OpenWeb())
                {
                    DataTable ToShowDt = CreateDataColumns("Form Name", "# Approved Today", "# Approved with Comments Today", "# Not Approved");
                    DataTable ToShow = CreateDataColumns("Approved", "Approved with Comments", "Not Approved");

                    string camQ = GetApprovalStatus();
                    DataTable dtLists = GetItemsOfSpecificTypeFromWeb(SPContext.Current.Site.ID, oWeb.ID, camQ, SPListTemplateType.Tasks);

                    if (dtLists.Rows.Count > 0)
                    {
                        try
                        {
                            var xx = (from r in dtLists.AsEnumerable()
                                      select r["ListId"]).Distinct().ToList();

                            SPList list = null;
                            int Appcnt = 0; int AppCmts = 0; int NotApp = 0;
                            foreach (string listId in xx)
                            {
                                SPListItemCollection lstimTasks = GetSPDocItemCollection(SPContext.Current.Site.ID, oWeb.ID, listId, camQ);

                                //List<string> ItemID = new List<string>();
                                //foreach (SPListItem dummy in lstimTasks)
                                //{
                                //    ItemID.Add(dummy["DocID"].ToString());
                                //}
                                //IEnumerable<string> distinctItemID = ItemID.Distinct();

                                //foreach (string ID in distinctItemID)
                                //{
                                //    SPListItem oDummyLstItem = oWeb.Lists[new Guid(listId)].GetItems(camQ)[0];
                                //}


                                foreach (SPListItem OlstItem in lstimTasks)
                                {
                                    SPFieldLookupValue app = new SPFieldLookupValue(Convert.ToString(OlstItem["Approval_x0020_Status"]));

                                    if (app.LookupValue == "Approved")
                                    {
                                        Appcnt++;
                                    }
                                    else if (app.LookupValue == "Approved with Comments")
                                    {
                                        AppCmts++;
                                    }
                                    else if (app.LookupValue == "Not Approved")
                                    {
                                        NotApp++;
                                    }
                                    if (!string.IsNullOrEmpty(Convert.ToString(OlstItem["DocLibID"])))
                                    {
                                        if (list == null)
                                        {
                                            list = oWeb.Lists[new Guid(Convert.ToString(OlstItem["DocLibID"]))];
                                        }
                                    }
                                }

                                if (list == null) { ToShowDt.Rows.Add("Library not found", Appcnt, AppCmts, NotApp); }
                                else
                                {
                                    ToShowDt.Rows.Add(list.Title, Appcnt, AppCmts, NotApp);
                                    list = null;
                                }
                            }
                        }
                        catch (Exception x)
                        {
                            ErrLos(x);
                        }
                    }
                    else
                    {
                        gvAppStatus.DataSource = null; gvAppStatus.DataBind(); gvAppStatus.Visible = false; errorMsg.Text = "No Records found"; errorMsg.ForeColor = System.Drawing.Color.Green;
                    }
                    gvAppStatus.DataSource = ToShowDt;
                    gvAppStatus.DataBind();
                }
                return gvAppStatus.Rows.Count;
            }
        }

        #region "Approval Status Manipulation"

        private string GetApprovalStatus()
        {
            return "<Where><Or><Eq><FieldRef Name=\"Approval_x0020_Status\" /><Value Type=\"Lookup\">Approved</Value></Eq><Or><Eq><FieldRef Name=\"Approval_x0020_Status\" />" +
                "<Value Type=\"Lookup\">Approved with Comments</Value></Eq><And><Eq><FieldRef Name=\"Approval_x0020_Status\" /><Value Type=\"Lookup\">Not Approved</Value></Eq>" +
                "<And><Eq><FieldRef Name=\"Document_x0020_Movement_x0020_St\" /><Value Type=\"Lookup\">Sent Back to CNT</Value></Eq><And><Eq><FieldRef Name=\"Document_x0020_Status\" />" +
                "<Value Type=\"Lookup\">Closed Out</Value></Eq><Eq><FieldRef Name=\"Modified\" /><Value IncludeTimeValue=\"false\" Type=\"DateTime\">" +
                "" + ToSPDate(Convert.ToString(DateTime.Today.ToShortDateString())) + "</Value></Eq></And></And></And></Or></Or></Where>";

            //return "<Where><Or><Eq><FieldRef Name=\"Approval_x0020_Status\" /><Value Type=\"Lookup\">Approved</Value></Eq><Or><Eq><FieldRef Name=\"Approval_x0020_Status\" />" +
            //    "<Value Type=\"Lookup\">Approved with Comments</Value></Eq><And><Eq><FieldRef Name=\"Approval_x0020_Status\" /><Value Type=\"Lookup\">Not Approved</Value></Eq>" +
            //    "<And><Eq><FieldRef Name=\"Document_x0020_Movement_x0020_St\" /><Value Type=\"Lookup\">Sent Back to CNT</Value></Eq><Eq><FieldRef Name=\"Document_x0020_Status\" />" +
            //    "<Value Type=\"Lookup\">Closed Out</Value></Eq></And></And></Or></Or></Where>";
        }

        private static string WFApprovalStatus(string wfStatus, string ddlPerson)
        {
            return "<Where><And><Eq><FieldRef Name=\"Approval_x0020_Status\" /><Value Type=\"Lookup\">" + wfStatus + "</Value></Eq><And><Eq><FieldRef Name=\"Document_x0020_Movement_x0020_St\" />" +
                "<Value Type=\"Lookup\">Sent Back to CNT</Value></Eq><And><Eq><FieldRef Name=\"Document_x0020_Status\" /><Value Type=\"Lookup\">Closed Out</Value></Eq><Eq>" +
                "<FieldRef Name=\"CreatedDt\" /><Value IncludeTimeValue=\"false\" Type=\"DateTime\">" + ToSPDate(Convert.ToString(DateTime.Today.ToString())) + "</Value></Eq></And>" +
                "</And></And></Where><OrderBy><FieldRef Name=\"Created\" Ascending=\"True\" /></OrderBy>";
        }

        #endregion

        private void DisableGridCells(GridView gvUserTask, DataTable ToShowDt)
        {
            gvUserTask.DataSource = ToShowDt;
            gvUserTask.DataBind();
            gvUserTask.HeaderRow.Cells[6].Visible = false;
            gvUserTask.HeaderRow.Cells[7].Visible = false;
            gvUserTask.HeaderRow.Cells[8].Visible = false;
            for (int i = 0; i < gvUserTask.Rows.Count; i++)
            {
                gvUserTask.Rows[i].Cells[6].Visible = false;
                gvUserTask.Rows[i].Cells[7].Visible = false;
                gvUserTask.Rows[i].Cells[8].Visible = false;
            }
            gvUserTask.Visible = true;
        }

        private bool ListExist(SPWeb oWeb, string guid)
        {
            try
            {
                SPList ckList = oWeb.Lists[new Guid(guid)];
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }


        private SPListItem getDocItems(SPWeb oWeb, SPListItem lstim, string DocLibID, string DocID)
        {
            SPListItem lstim2 = null;
            try
            {
                lstim2 = oWeb.Lists[new Guid(lstim["DocLibID"].ToString())].GetItemById(int.Parse(lstim["DocID"].ToString()));
                return lstim2;
            }
            catch (Exception x)
            {
                ErrLogs(x);
                return null;
            }

        }

        private static string WFStatus(string wfStatus, string ddlPerson)
        {
            return "<Where><And><Eq><FieldRef Name=\"AssignedTo\" /><Value Type=\"User\">" + ddlPerson + "</Value></Eq><Eq><FieldRef Name=\"Status\" />" +
                "<Value Type=\"Choice\">" + wfStatus + "</Value></Eq></And></Where><OrderBy><FieldRef Name=\"Modified\" Ascending=\"False\" /></OrderBy>";
        }

        private static String ToSPDate(String strDt)
        {
            if (strDt == String.Empty)
                return strDt;
            else
                return (Convert.ToDateTime(strDt)).ToString("yyyy-MM-dd");
        }

        public void getEntityUsers(DropDownList ddlTaskPerson, string Entity)
        {

            try
            {
                using (SPSite oSite = new SPSite(SPContext.Current.Site.Url))
                {
                    using (SPWeb oWeb = oSite.OpenWeb())
                    {
                        SPListItemCollection oLstItemColl = oWeb.Lists.TryGetList("Users Master").GetItems(GetEntityUser(Entity));
                        foreach (SPListItem oLstItem in oLstItemColl)
                        {
                            SPFieldUserValue Users = new SPFieldUserValue(oWeb, Convert.ToString(oLstItem["UserName"]));
                            //ddlTaskPerson.Items.Add(new ListItem(Convert.ToString(oLstItem["User_x0020_Name"]), Convert.ToString(Users.User)));
                            string user = Users.LookupValue; string[] users = user.Split('\\'); var e = from s in users select s; int c = e.Count();
                            string userName = null;
                            if (c > 1) userName = users[1]; else userName = user;
                            ddlTaskPerson.Items.Add(new ListItem(userName, Users.LookupValue));
                        }
                    }
                }
            }
            catch (Exception x)
            {
                ErrLos(x);
            }

        }

        private SPQuery GetEntityUser(string Entity)
        {
            SPQuery qry = new SPQuery();
            qry.Query = "<Where><Eq><FieldRef Name=\"Entity_x0020_Lookup\" /><Value Type=\"Lookup\">" + Entity + "</Value></Eq></Where>";
            return qry;
        }

        #region "Error Logs"

        private void ErrLogs(Exception x)
        {
            SPSite Osite = new SPSite(SPContext.Current.Site.ID);
            SPWeb oWeb = Osite.OpenWeb();
            SPListItem oLstItem = oWeb.Lists.TryGetList("ErrorLogs").AddItem();
            oWeb.AllowUnsafeUpdates = true;
            oLstItem["Errors"] = Convert.ToString(x.Message);
            oLstItem.Update();
            oWeb.AllowUnsafeUpdates = false;
            Osite.Dispose();
        }

        public void ErrLos(Exception x)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite Osite = new SPSite(SPContext.Current.Site.Url))
                    {
                        using (SPWeb oWeb = Osite.OpenWeb())
                        {
                            SPList oList = oWeb.Lists.TryGetList("ErrorLogs");
                            if (oList != null)
                            {
                                oWeb.AllowUnsafeUpdates = true;
                                SPListItem oLstItem = oList.AddItem();
                                oLstItem["Errors"] = Convert.ToString(x.Message);
                                oLstItem.Update();
                                oWeb.AllowUnsafeUpdates = false;
                            }
                            else
                            {
                                errorMsg.Text = "Error logs list not found"; errorMsg.ForeColor = System.Drawing.Color.Red;
                            }
                        }
                    }
                });
            }
            catch (Exception xy)
            {
                errorMsg.Text = xy.Message; errorMsg.ForeColor = System.Drawing.Color.Red;
            }

        }

        #endregion

        public string GetUserEntity()
        {
            string e = null;
            try
            {
                SPQuery qry = new SPQuery();
                qry.Query = "<Where><Eq><FieldRef Name=\"UserName\" /><Value Type=\"User\">" + SPContext.Current.Web.CurrentUser.LoginName + "</Value></Eq></Where>";

                SPListItem oListItem = SPContext.Current.Web.Lists.TryGetList("Users Master").GetItems(qry)[0];
                SPFieldLookupValue entity = new SPFieldLookupValue(Convert.ToString(oListItem["Entity Lookup"]));
                if (entity.LookupValue == "Contractor")
                    e = "CNT";
                else if (entity.LookupValue == "Consultant")
                    e = "CNS";
                else if (entity.LookupValue == "Client")
                    e = "CLN";
                else
                    e = "ENT";
            }
            catch (Exception x)
            {
                ErrLos(x);
            }
            return e;
        }

    }
}
